package com.xpf.shardingtabledemo.shardingdtable;

import com.xpf.shardingtabledemo.shardingdtable.annotion.NeedShardedTable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Lenovo
 */
@Order(18)
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
public class ShardingTableInterceptor implements Interceptor ,
        ApplicationListener<ContextRefreshedEvent> {

    private ConcurrentHashMap<String,Class<?>> classMap = new ConcurrentHashMap();
    private HashSet<String> returnSet = new HashSet<>();

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactories;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取原始的 SQL 语句和参数
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String mappeid = mappedStatement.getId();
        if (mappeid == null || returnSet.contains(mappeid)) {
            return invocation.proceed();
        }
        Class<?> mappClass = classMap.get(mappeid);
        if (mappClass == null) {
            try {
                mappClass = Class.forName(mappeid.substring(0,mappeid.lastIndexOf(".")));
            } catch (ClassNotFoundException e) {
                returnSet.add(mappeid);
            }
            if (mappeid != null && mappClass != null) {
                classMap.put(mappeid,mappClass);
            }
            if (mappClass == null) {
                if (mappeid != null) {
                    returnSet.add(mappeid);
                }
                return invocation.proceed();
            }
        }
        try {
            NeedShardedTable annotation = AnnotationUtils.findAnnotation(mappClass, NeedShardedTable.class);
            if (annotation != null) {
                Object parameter = invocation.getArgs()[1];
                BoundSql boundSql = mappedStatement.getBoundSql(parameter);
                String originalSql = boundSql.getSql();
                // 根据分表策略修改表名
                String modifiedSql = modifyTableName(originalSql, annotation);
                // 更新 BoundSql 对象中的 SQL
                BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), modifiedSql,
                        boundSql.getParameterMappings(), boundSql.getParameterObject());
                MappedStatement newMappedStatement = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
                invocation.getArgs()[0] = newMappedStatement;
                Object result = invocation.proceed();
                return result;
            } else {
                returnSet.add(mappeid);
            }
        } catch (Exception e) {
            log.error("分表拦截出错： " + e.getMessage(),e);
        }

        return invocation.proceed();
    }

    // 根据分表策略修改表名的方法
    private String modifyTableName(String originalSql, NeedShardedTable shardedTable) {
        // 根据分表策略获取实际的表名
        String actualTableName = shardedTable.strategy().getShardingTableStrategy().getActualTableName(shardedTable.tableName());
        String modifiedSql = originalSql.replace(shardedTable.tableName(), actualTableName);
        return modifiedSql;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }


    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource,
                ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        builder.keyProperty(StringUtils.join(ms.getKeyProperties(), ","));
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        for (SqlSessionFactory factory : sqlSessionFactories) {
            if (!factory.getConfiguration().getInterceptors().contains(this))
                factory.getConfiguration().addInterceptor(this);
        }
        log.info("【分表插件】插件注册完成.");
    }

    private static class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
}
